import {
  reqGetUsers,
  reqAddUser,
  reqUpdateUser,
  reqDeleteUser,
} from '../../api/users'
import { Message } from 'element-ui'

const state = {
  users: [],
  total: 0,
}

const getters = {}

const actions = {
  getUsers({ commit }, { page, limit }) {
    reqGetUsers(page, limit)
      .then((res) => {
        commit('GET_USERS', res.data.data)
      })
      .catch((e) => {
        Message({
          type: 'error',
          message: e.message,
        })
      })
  },
  async addUser({ commit }, user) {
    try {
      const res = await reqAddUser(user)
      if (res.data.code === 20000) {
        commit('GET_USERS', state)
      } else {
        Message({
          type: 'error',
          message: res.data.message,
        })
        return Promise.reject()
      }
    } catch (e) {
      Message({
        type: 'error',
        message: e.message,
      })
    }

    // reqAddUser(user)
    //   .then((res) => {
    //     if (res.data.code === 20000) {
    //       commit('GET_USERS', state)
    //     } else {
    //       Message({
    //         type: 'error',
    //         message: res.data.message,
    //       })
    //     }
    //   })
    //   .catch((e) => {
    //     Message({
    //       type: 'error',
    //       message: e.message,
    //     })
    //   })
  },
  async updateUser({ commit }, user) {
    try {
      const res = await reqUpdateUser(user)
      if (res.data.code === 20000) {
        commit('GET_USERS', state)
      } else {
        Message({
          type: 'error',
          message: res.data.message,
        })
        return Promise.reject()
      }
    } catch (e) {
      Message({
        type: 'error',
        message: e.message,
      })
    }
  },
  async deleteUser({ commit }, id) {
    reqDeleteUser(id)
      .then((res) => {
        if (res.data.code === 20000) {
          commit('GET_USERS', state)
        }
      })
      .catch((e) => {
        Message({
          type: 'error',
          message: e.message,
        })
      })
  },
}

const mutations = {
  GET_USERS(state, data) {
    state.users = data.users
    state.total = data.total
  },
}

export default {
  namespaced: true,
  getters,
  state,
  actions,
  mutations,
}
